package com.zhdl.websocket.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * websocket服务
 *
 * @Description:
 * @author: liu zhenming
 * @date: 2023/7/20 10:51
 */
@Slf4j
@Component
@ServerEndpoint("/ws")
public class WebSocketServer {


    @OnOpen
    public void onOpen(Session session) {
        // WebSocket 连接建立时调用
        log.info("WebSocket connection opened: " + session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // 接收到客户端发送的消息时调用
        log.info("WebSocket connection onMessage: id: {} Received message: {}", session.getId(), message);
        // 回复消息给客户端
        session.getAsyncRemote().sendText("WebSocket Received: " + message);

    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        //客户端关闭时调用
        log.info("WebSocket connection onClose: " + session.getId());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        //客户端异常时调用
        log.error("ws : onError id: {} throwable : [{}]", session.getId(), throwable.getMessage());
    }


}
